const config = require('./config');

const solChain = require('./SolChain');
const idl = require("./idl/basic_1.json");
const {   
    Program,
    AnchorProvider,
    BN,
    web3,
    Wallet,
} = require("@coral-xyz/anchor");


const {  
    Connection,
    clusterApiUrl,
    PublicKey,
    Keypair
} = require('@solana/web3.js')
const {
    getKeyPairUser1, getKeyPairUser2
} = require('./MyKeypair');

const BaseProgram = require('./BaseProgram');

const MpcVersionedTransaction = require('./MpcVersionedTransaction');
function transactionMessage(payerPubKey, recentBlockHash, instructions) {
    console.log('payerPubKey: ', payerPubKey);
    let messageV0 = new web3.TransactionMessage({payerKey:payerPubKey, recentBlockhash:recentBlockHash, instructions:instructions}).compileToV0Message();
    const transaction = new MpcVersionedTransaction(messageV0);
    return transaction;
}
const run = async () => {
    const user1Kp = await getKeyPairUser1();
    const user2Kp = await getKeyPairUser2();

    const wallet = new Wallet(user2Kp);

    const program = new BaseProgram(solChain.connection, wallet, idl, config.local_programID);
    const myAccount = web3.Keypair.generate();
    const instruction = await program.methodsInstruction("initialize", new BN(2345),{
        myAccount: myAccount.publicKey,
        user: user2Kp.publicKey,
        systemProgram: web3.SystemProgram.programId,});

    let latestBlockhash = await solChain.getLatestBlockhash();

    let payerPk = user2Kp.publicKey;

    //console.log('payPk: ', payerPk.toBase58())
    

    let tx = transactionMessage(payerPk, latestBlockhash.blockhash, [instruction]);
    console.log('tx: ', tx);

    const myWallet = new Wallet(myAccount);
    
    tx = await wallet.signTransaction(tx);
    tx = await myWallet.signTransaction(tx);
     
    //tx.sign([ myAccount, user2Kp]);
    let rawTx = tx.serialize();
    console.log('rawTx: ', rawTx);
    let txid = await solChain.sendRawTransaction(rawTx)

    console.log("txId : ", txid);
        
}
run();